package com.mlog.njyjy.ndop.monitor.collector.processor;

import com.mlog.njyjy.ndop.monitor.collector.dao.TaskRepository;
import com.mlog.njyjy.ndop.monitor.common.domain.Task;
import com.mlog.njyjy.ndop.monitor.common.support.Constants;
import com.mlog.njyjy.ndop.monitor.common.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;

import java.time.LocalDate;

/**
 * 消费到消息后的处理
 *
 * @author zyz
 * @version v1.0, 2020/07/29
 */
@Slf4j
public class ScanProcessor implements Processor {

    private Task task;

    private TaskRepository taskRepository;

    public ScanProcessor(Task task, TaskRepository taskRepository) {
        this.task = task;
        this.taskRepository = taskRepository;
    }

    @Override
    public void process(Exchange exchange) throws Exception {
        log.info("The specified product: {} has been scanned", task.getProductName());
        //判断更新时间是否是今天
        long lastModifyTime = (long) exchange.getMessage().getHeader(Exchange.FILE_LAST_MODIFIED);
        if (DateTimeUtil.fromTimestamp(lastModifyTime).toLocalDate().equals(LocalDate.now())) {
            //判断文件大小
            long size = (long) exchange.getMessage().getHeader(Exchange.FILE_LENGTH);
            if (size > 0) {
                //TODO: 修改产品状态
                task.setProductStatus(Constants.PRODUCT_STATUS_HAVE_REACHED);
            } else {
                task.setProductStatus(Constants.PRODUCT_STATUS_ERROR_REACHED);

            }
            boolean succeed = taskRepository.update(task);
            if (succeed) {
                log.info("产品 {} 到达状态修改成功", exchange.getMessage().getHeader(Exchange.FILE_NAME));
            } else {
                log.warn("产品 {} 到达状态修改失败", exchange.getMessage().getHeader(Exchange.FILE_NAME));
            }
            log.info("end scan, today's product:{} 已到达", task.getProductName());
        }
    }
}
